﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace NB.MGJ.Common.Helper
{
    public static class WipeNullHelper
    {
        /// <summary>
        /// 把对象里的null变成相应类型的默认值
        /// </summary>
        /// <param name="entity">对象实体</param>
        /// <returns></returns>
        public static T WipeNull<T>(T entity)
        {
            System.Reflection.PropertyInfo[] ps = entity.GetType().GetProperties();
            Type type = entity.GetType();
            foreach (PropertyInfo propertie in ps)
            {
                if (propertie.PropertyType == typeof(string))
                {
                    PropertyInfo propertyInfo = type.GetProperty(propertie.Name);
                    if (propertyInfo.GetValue(entity, null) == null)
                    {
                        propertyInfo.SetValue(entity, "", null);
                    }
                }
                else if (propertie.PropertyType == typeof(Int32))
                {
                    PropertyInfo propertyInfo = type.GetProperty(propertie.Name);
                    if (propertyInfo.GetValue(entity, null) == null)
                    {
                        propertyInfo.SetValue(entity, 0, null);
                    }
                }
                else if (propertie.PropertyType == typeof(Nullable<int>))
                {
                    PropertyInfo propertyInfo = type.GetProperty(propertie.Name);
                    if (propertyInfo.GetValue(entity, null) == null)
                    {
                        propertyInfo.SetValue(entity, 0, null);
                    }
                }
                else if (propertie.PropertyType == typeof(decimal))
                {
                    PropertyInfo propertyInfo = type.GetProperty(propertie.Name);
                    if (propertyInfo.GetValue(entity, null) == null)
                    {
                        propertyInfo.SetValue(entity, Convert.ToDecimal(0.0), null);
                    }
                }
                else if (propertie.PropertyType == typeof(Nullable<decimal>))
                {
                    PropertyInfo propertyInfo = type.GetProperty(propertie.Name);
                    if (propertyInfo.GetValue(entity, null) == null)
                    {
                        propertyInfo.SetValue(entity, Convert.ToDecimal(0.0), null);
                    }
                }
            }
            return entity;
        }

    }
}
